package com.tiancheng.trade.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.payment.bo.OrgPaymentChannelDetailBO;
import com.tiancheng.trade.payment.mapper.OrgPaymentChannelMapper;
import com.tiancheng.trade.payment.model.OrgPaymentChannel;
import com.tiancheng.trade.payment.service.OrgPaymentChannelService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Author: kellen
 * @Description: 机构支付渠道 service
 * @Date: create in 2024/11/20 10:23
 */
@Service
public class OrgPaymentChannelServiceImpl extends ServiceImpl<OrgPaymentChannelMapper, OrgPaymentChannel> implements OrgPaymentChannelService {

    private static List<OrgPaymentChannelDetailBO> allOrgPaymentChannels;

    @Override
    public void newRecord(OrgPaymentChannel orgPaymentChannel) {
        final long count = this.count(new LambdaQueryWrapper<OrgPaymentChannel>().eq(OrgPaymentChannel::getPaymentChannelId, orgPaymentChannel.getPaymentChannelId()).eq(OrgPaymentChannel::getOrganizationCode, orgPaymentChannel.getOrganizationCode()));
        BusinessErrorInfoEnum.PAYMENT_CHANNEL_ADD_ERROR.assertIsTrue(count == 0);
        orgPaymentChannel.setIsEnable(1);
        this.save(orgPaymentChannel);
    }

    @Override
    public List<OrgPaymentChannelDetailBO> queryAllOrgPaymentChannelInfo() {
        if (CollectionUtils.isEmpty(allOrgPaymentChannels)) {
            synchronized (this) {
                if (CollectionUtils.isEmpty(allOrgPaymentChannels)) {
                    allOrgPaymentChannels = baseMapper.queryAllOrgPaymentChannelInfo();
                }
            }
        }
        return allOrgPaymentChannels;
    }

    @Override
    public OrgPaymentChannelDetailBO queryAllOrgPaymentChannelInfoById(Long id) {
        final List<OrgPaymentChannelDetailBO> orgPaymentChannelDetailBOS = queryAllOrgPaymentChannelInfo();
        BusinessErrorInfoEnum.PAYMENT_ORDER_ORG_PAY_CHANNEL_ERROR.assertIsTrue(CollectionUtils.isNotEmpty(orgPaymentChannelDetailBOS));
        final Optional<OrgPaymentChannelDetailBO> first = orgPaymentChannelDetailBOS.stream().filter(c -> c.getId().equals(id)).findFirst();
        BusinessErrorInfoEnum.PAYMENT_ORDER_ORG_PAY_CHANNEL_ERROR.assertIsTrue(first.isPresent());
        return first.get();
    }
}
